package com.seckill.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.seckill.domain.Product;
import com.seckill.mapper.ProductMapper;
import com.seckill.service.ProductService;
import com.seckill.utils.R;
import com.seckill.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Override
    public List<Product> getAllProducts() {
        return productMapper.findAll();
    }

    @Override
    public R getProductPage(ProductVo productVo) {
        List<Product> all = getAllProducts();
        int fromIndex = (productVo.getPage() - 1) * productVo.getLimit();
        int toIndex = Math.min(fromIndex + productVo.getLimit(), all.size());
        List<Product> pageList = fromIndex >= all.size() ? new ArrayList<>() : all.subList(fromIndex, toIndex);
        Map<String, Object> result = new HashMap<>();
        result.put("total", all.size());
        result.put("page", productVo.getPage());
        result.put("size", productVo.getLimit());
        result.put("list", pageList);
        return R.OK(result);
    }

    @Override
    public R uplodFile(MultipartFile file) {


        try {
            String extName = FileNameUtil.extName(file.getOriginalFilename());
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extName, null);
            String url = "http://39.101.78.210:8080/" + storePath.getFullPath();
            return R.OK(url);
        } catch (IOException e) {
            return R.ERROR(500,"上传失败");
        }


    }

    @Override
    public Product getProductById(Long id) {
        Product product = productMapper.selectById(id);
        return product;
    }
} 